JavaScript Form Handling

1. What is Form Handling?

Form handling means collecting user input from HTML forms and processing it using JavaScript. It allows validation, data submission, and interaction without reloading the page.

2. Types of Form Handling

1. Using form elements (name, id)
2. Using JavaScript Events
3. Using FormData Object

3. Basic Syntax

document.getElementById("myForm").addEventListener("submit", function(e){
    e.preventDefault();
});
    

4. Example: Simple Form Handling

let form = document.getElementById("myForm");
let output = document.getElementById("output");

form.addEventListener("submit", function(e){
    e.preventDefault();

    let username = document.getElementById("username").value;
    let email = document.getElementById("email").value;

    output.innerText = "Username: " + username + 
                       ", Email: " + email;
});
    

5. FormData Object

let formData = new FormData(document.getElementById("myForm"));
document.write(formData.get("username"));
    

6. Comparison Table

Method Use Difficulty
Direct Element Access Small forms Easy
Event Listener Validation & control Medium
FormData Large forms / APIs Advanced
✅ Tip: Always use e.preventDefault() to stop page reload during form submission.

Practice Questions

Test your understanding of JavaScript Form Handling.

Easy

Q1: Prevent default form submission.

  • Assume you have a form element selected as form.
  • Add a submit event listener to it.
  • Write the code to prevent the page from reloading.
Easy

Q2: Get the value of an input field.

  • Assume there is an input field with the ID username.
  • Select the element using its ID.
  • Retrieve its current value and log it to the console.
Medium

Q3: Create a FormData object.

  • Assume you have a form element with the ID myForm.
  • Select the form element.
  • Create a new FormData object from this form.
Medium

Q4: Listen for real-time input changes.

  • Select an input field with the ID email.
  • Add an event listener that triggers every time the user types a character.
  • Log "Input changed!" to the console inside the listener.
Hard

Q5: Retrieve a specific value from FormData.

  • Assume you have a FormData object named data.
  • Write the code to retrieve the value associated with the name="password" attribute.
  • Log the retrieved value to the console.

Answer

Code: